<script setup lang="tsx">
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  reactive,
  toRaw,
  toRef
} from "vue";
import { useRouter, useRoute } from "vue-router";
import type {
  comType,
  EthernetType,
  loraType,
  LTEDataType,
  WiFiType
} from "./utils/type";
const router = useRouter();

import { useRole } from "./utils/hook";
import ComForm from "./utils/ComForm.vue";
const treeRef = ref();
const tableRef = ref();

const { form, loading, homeData, onSearch, interfaces } = useRole();
import {
  getInterfaceSortRead,
  interfaceUpdate
} from "@/api/communicationInterface";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { getHomeData } from "@/api/home";
const selectedItem = ref(null);

// 定义 LTEData 的结构
const LTEData = ref<LTEDataType>({
  id: null,
  apnName: "",
  apnPassword: "",
  apnUser: "",
  authType: "",
  netWorkMode: ""
});
// 定义Ethernet的结构数据
const Ethernet1 = ref<EthernetType>({
  id: 0,
  interfaceName: "",
  interfacePar: {
    dhcpEnable: "",
    gateway: "",
    ipAddress: "",
    mac: "",
    subnetMask: ""
  }
});
const Ethernet2 = ref<EthernetType>({
  id: 0,
  interfaceName: "",
  interfacePar: {
    dhcpEnable: "",
    gateway: "",
    ipAddress: "",
    mac: "",
    subnetMask: ""
  }
});
const wifi = ref<WiFiType>({
  id: 0,
  interfaceName: "",
  interfacePar: {
    dhcpEnable: "",
    gateway: "",
    ipAddress: "",
    mac: "",
    subnetMask: "",
    apnUser: "",
    apnPassword: ""
  }
});

function createCom(): comType {
  return {
    id: 0,
    interfaceName: "",
    interfacePar: {
      baudRate: 0,
      dataBits: 0,
      frameBreakTime: 0,
      parity: 0,
      stopBits: 0
    },
    workMode: 0
  };
}
const com1 = ref<comType>(createCom());
const com2 = ref<comType>(createCom());
const com3 = ref<comType>(createCom());
const com4 = ref<comType>(createCom());
const com5 = ref<comType>(createCom());
const com6 = ref<comType>(createCom());
const com7 = ref<comType>(createCom());
const com8 = ref<comType>(createCom());
const lora = ref<loraType>({
  id: 0,
  interfaceName: "",
  interfacePar: {
    transmissionMode: 0,
    frameBreakTime: 0,
    channel: 0,
    address: 0,
    dataEncryption: 0,
    netID: 0,
    workMode: 0,
    airRate: 0
  }
});
// 上面的消息通知
const route = useRoute();
onMounted(() => {
  // onSearch();
  // console.log("ceshidayin", route.query);
  if (route.query.item) {
    if (route.query.item == "FourthGeneration") {
      select_item("FourthGeneration", "LTE");
    } else {
      select_item(route.query.item, route.query.item);
    }
    return;
  }
  if (interfaces) {
    getHomeData().then(data => {
      const keys = Object.keys(data.data.interfaces);
      const firstKey = keys[0];
      setTimeout(() => {
        if (firstKey == "FourthGeneration") {
          select_item("FourthGeneration", "LTE");
        } else {
          select_item(firstKey, firstKey);
        }
      }, 500);
    });
  }

  // }
});
function select_item(value, param) {
  selectedItem.value = value;
  getInterfaceSortRead({ interfaceName: param })
    .then(data => {
      // 在这里使用数据
      // 4G
      if (param === "LTE" && data.data) {
        const lteData = data.data as Partial<LTEDataType>; // 使用 Partial 允许部分字段存在
        LTEData.value.id = lteData.id || 0;
        LTEData.value.apnName = lteData.apnName || "";
        LTEData.value.apnPassword = lteData.apnPassword || "";
        LTEData.value.apnUser = lteData.apnUser || "";
        LTEData.value.authType = lteData.authType || "";
        LTEData.value.netWorkMode = lteData.netWorkMode || "";
      } else if (param === "Ethernet" && data.data) {
        // 点击了ethernet
        const ethernetData = data.data as unknown as EthernetType[]; // 强制类型转换
        Ethernet1.value = (ethernetData[0] || {}) as EthernetType; // 显式类型断言
        Ethernet2.value = (ethernetData[1] || {}) as EthernetType; // 显式类型断言
      } else if (param === "WiFi" && data.data) {
        // WiFi
        const wifiData = data.data as Partial<WiFiType>;
        wifi.value = wifiData[0] as WiFiType;
      } else if (param === "COM" && data.data) {
        // com 最多8个
        const coms = [com1, com2, com3, com4, com5, com6, com7, com8];
        const comData = data.data as unknown as comType[]; // 强制类型转换
        com1.value = (comData[0] || {}) as comType; // 显式类型断言
        com2.value = (comData[1] || {}) as comType; // 显式类型断言
        for (let i = 0; i < comData.length; i++) {
          if (comData[i]) {
            coms[i].value = comData[i]; // 直接赋值
          } else {
            coms[i].value = {} as comType; // 如果没有数据则赋空对象
          }
        }
      } else if (param === "LoRa" && data.data) {
        // lora
        const loraData = data.data as Partial<loraType>;
        lora.value = loraData[0] as loraType;
      }
    })
    .catch(error => {
      console.error("发生错误:", error); // 处理可能的错误
    });
}
function updateFourthGeneration() {
  ElMessageBox.confirm(`确认应用配置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 处理确认操作
      const data = interfaceUpdate(toRaw(LTEData.value));
      if (data) {
        select_item("FourthGeneration", "LTE");
        message("4g/lte修改成功", { type: "success" });
      }
    })
    .catch(() => {});
}

function updateEthernet(num) {
  ElMessageBox.confirm(`确认应用配置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 处理确认操作
      let data;
      if (num == 1) {
        data = interfaceUpdate(toRaw(Ethernet1.value));
      } else {
        data = interfaceUpdate(toRaw(Ethernet2.value));
      }
      if (data) {
        select_item("Ethernet", "Ethernet");
        message("修改成功", { type: "success" });
      }
    })
    .catch(() => {});
}
function updateWiFi() {
  ElMessageBox.confirm(`确认应用配置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 处理确认操作
      const data = interfaceUpdate(toRaw(wifi.value));
      if (data) {
        select_item("WiFi", "WiFi");
        message("修改成功", { type: "success" });
      }
    })
    .catch(() => {});
}
function updateCom({ index, data }) {
  ElMessageBox.confirm(`确认应用配置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    // 处理确认操作
    const data1 = interfaceUpdate(toRaw(data));
    if (data1) {
      select_item("COM", "COM");
      message("修改成功", { type: "success" });
    }
  });
}
function updateLoRa() {
  ElMessageBox.confirm(`确认应用配置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    // 处理确认操作
    lora.value.interfacePar.netID = Number(lora.value.interfacePar.netID);
    lora.value.interfacePar.channel = Number(lora.value.interfacePar.channel);
    lora.value.interfacePar.address = Number(lora.value.interfacePar.address);
    interfaceUpdate(toRaw(lora.value))
      .then(data => {
        if (data.code && data.code === 200) {
          select_item("LoRa", "LoRa");
          message("修改成功", { type: "success" });
        } else {
          // 处理其他状态码
          console.error(`请求失败，状态码: ${data.code}, 消息: ${data.msg}`);
        }
      })
      .catch(error => {
        console.error("发生错误:", error); // 处理可能的错误
      });
  });
}

onUnmounted(() => {});
defineOptions({
  name: "CommunicationInterface"
});
</script>

<template>
  <div v-loading="loading" element-loading-text="加载中..." class="content">
    <div class="content_left">
      <div
        v-if="interfaces && interfaces.FourthGeneration !== 0"
        :class="{
          interfaces_item: true,
          active: selectedItem === 'FourthGeneration'
        }"
        @click="select_item('FourthGeneration', 'LTE')"
      >
        4G
      </div>
      <div
        v-if="interfaces && interfaces.Ethernet !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'Ethernet' }"
        @click="select_item('Ethernet', 'Ethernet')"
      >
        Ethernet
      </div>
      <div
        v-if="interfaces && interfaces.WiFi !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'WiFi' }"
        @click="select_item('WiFi', 'WiFi')"
      >
        WiFi
      </div>
      <div
        v-if="interfaces && interfaces.COM !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'COM' }"
        @click="select_item('COM', 'COM')"
      >
        COM
      </div>
      <div
        v-if="interfaces && interfaces.LoRa !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'LoRa' }"
        @click="select_item('LoRa', 'LoRa')"
      >
        LoRa
      </div>
      <div
        v-if="interfaces && interfaces.Zigbee !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'Zigbee' }"
        @click="select_item('Zigbee', '')"
      >
        Zigbee
      </div>
      <div
        v-if="interfaces && interfaces.Local !== 0"
        :class="{ interfaces_item: true, active: selectedItem === 'Local' }"
        @click="select_item('Local', '')"
      >
        Local
      </div>
    </div>
    <div class="content_right">
      <!-- {{ interfaces }} -->
      <div v-if="selectedItem == 'FourthGeneration'">
        <el-card shadow="never">
          <h3>APN</h3>
          <el-form label-position="top" :model="LTEData" class="right_form">
            <el-row :gutter="40">
              <el-col :span="5">
                <el-form-item prop="apnName" label="APN名称">
                  <el-input v-model="LTEData.apnName" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="authType" label="认证方式">
                  <el-select v-model="LTEData.authType">
                    <el-option label="NONE" value="0" />
                    <el-option label="PAP" value="1" />
                    <el-option label="CHAP" value="2" />
                    <el-option label="PAP_OR_CHAP" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="apnUser" label="用户名">
                  <el-input v-model="LTEData.apnUser" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="apnPassword" label="密码">
                  <el-input v-model.number="LTEData.apnPassword" />
                </el-form-item>
              </el-col>
            </el-row>
            <h3>网络模式-5G</h3>
            <el-row :gutter="40" :align="'middle'">
              <el-col :span="5">
                <el-form-item prop="netWorkMode" label="网络模式">
                  <el-select v-model="LTEData.netWorkMode">
                    <el-option label="Auto" value="0" />
                    <el-option label="NSA" value="1" />
                    <el-option label="SA" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" @click="updateFourthGeneration">
                  应用
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div v-else-if="selectedItem == 'Ethernet'">
        <!-- Ethernet1 -->
        <el-card shadow="never">
          <h3>{{ Ethernet1.interfaceName }}</h3>
          <el-form label-position="top" :model="Ethernet1" class="right_form">
            <el-row :gutter="40">
              <el-col :span="5">
                <el-form-item prop="authType" label="自动获取IP">
                  <el-select v-model="Ethernet1.interfacePar.dhcpEnable">
                    <el-option label="OFF" value="0" />
                    <el-option label="ON" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="ipAddress" label="IP">
                  <el-input v-model="Ethernet1.interfacePar.ipAddress" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="subnetMask" label="子网掩码">
                  <el-input v-model="Ethernet1.interfacePar.subnetMask" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="gateway" label="默认网关">
                  <el-input v-model="Ethernet1.interfacePar.gateway" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="mac" label="MAC">
                  <el-input v-model="Ethernet1.interfacePar.mac" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" @click="updateEthernet(1)">
                  应用
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <!-- Ethernet2 -->
        <el-card v-if="Ethernet2.id" shadow="never" class="mt-4">
          <h3>{{ Ethernet2.interfaceName }}</h3>
          <el-form label-position="top" :model="Ethernet2" class="right_form">
            <el-row :gutter="40">
              <el-col :span="5">
                <el-form-item prop="authType" label="自动获取IP">
                  <el-select v-model="Ethernet2.interfacePar.dhcpEnable">
                    <el-option label="OFF" value="0" />
                    <el-option label="ON" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="ipAddress" label="IP">
                  <el-input v-model="Ethernet2.interfacePar.ipAddress" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="subnetMask" label="子网掩码">
                  <el-input v-model="Ethernet2.interfacePar.subnetMask" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="gateway" label="默认网关">
                  <el-input v-model="Ethernet2.interfacePar.gateway" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="mac" label="MAC">
                  <el-input v-model="Ethernet2.interfacePar.mac" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" @click="updateEthernet(2)">
                  应用
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div v-else-if="selectedItem == 'COM'" class="com_item">
        <ComForm
          v-if="com1.id"
          :com="com1"
          :index="1"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com2.id"
          :com="com2"
          :index="2"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com3.id"
          :com="com3"
          :index="3"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com4.id"
          :com="com4"
          :index="4"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com5.id"
          :com="com5"
          :index="5"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com6.id"
          :com="com6"
          :index="6"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com7.id"
          :com="com7"
          :index="7"
          @update-com="updateCom"
        />
        <ComForm
          v-if="com8.id"
          :com="com8"
          :index="8"
          @update-com="updateCom"
        />
      </div>
      <div v-else-if="selectedItem == 'LoRa'">
        <el-card shadow="never">
          <h3>{{ lora.interfaceName }}</h3>
          <el-form label-position="top" :model="lora" class="right_form">
            <el-row :gutter="40">
              <el-col :span="5">
                <el-form-item prop="channel" label="通信通道">
                  <el-input v-model="lora.interfacePar.channel" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="netID" label="网络ID">
                  <el-input v-model="lora.interfacePar.netID" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="address" label="模块地址">
                  <el-input v-model="lora.interfacePar.address" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="airRate" label="空中速率">
                  <el-select v-model="lora.interfacePar.airRate">
                    <el-option label="0.3Kbps" :value="300" />
                    <el-option label="1.2Kbps" :value="1200" />
                    <el-option label="2.4Kbps" :value="2400" />
                    <el-option label="4.8Kbps" :value="4800" />
                    <el-option label="9.6Kbps" :value="9600" />
                    <el-option label="19.2Kbps" :value="192000" />
                    <el-option label="38.4Kbps" :value="384000" />
                    <el-option label="62.5Kbps" :value="625000" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="transmissionMode" label="传输模式">
                  <el-select v-model="lora.interfacePar.transmissionMode">
                    <el-option label="定点" :value="0" />
                    <el-option label="透传" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="dataEncryption" label="数据加密">
                  <el-select v-model="lora.interfacePar.dataEncryption">
                    <el-option label="OFF" :value="0" />
                    <el-option label="ON" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="frameBreakTime" label="断帧时间">
                  <el-select v-model="lora.interfacePar.frameBreakTime">
                    <el-option label="Auto" :value="0" />
                    <el-option label="20" :value="20" />
                    <el-option label="30" :value="30" />
                    <el-option label="50" :value="50" />
                    <el-option label="100" :value="100" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="workMode" label="模式">
                  <el-select v-model="lora.interfacePar.workMode">
                    <el-option label="边缘采集" :value="0" />
                    <el-option label="透传" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" @click="updateLoRa"> 应用 </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div v-else-if="selectedItem == 'Local'">
        Local {{ interfaces.Local }}
      </div>
      <div v-else-if="selectedItem == 'WiFi'">
        <el-card shadow="never">
          <h3>{{ wifi.interfaceName }}</h3>
          <el-form label-position="top" :model="wifi" class="right_form">
            <el-row :gutter="40">
              <el-col :span="5">
                <el-form-item prop="apnUser" label="用户">
                  <el-input v-model="wifi.interfacePar.apnUser" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="apnPassword" label="密码">
                  <el-input v-model="wifi.interfacePar.apnPassword" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="authType" label="自动获取IP">
                  <el-select v-model="wifi.interfacePar.dhcpEnable">
                    <el-option label="OFF" value="0" />
                    <el-option label="ON" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="ip" label="IP">
                  <el-input v-model="wifi.interfacePar.ipAddress" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="subnetMask" label="子网掩码">
                  <el-input v-model="wifi.interfacePar.subnetMask" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="gateway" label="默认网关">
                  <el-input v-model="wifi.interfacePar.gateway" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="mac" label="MAC">
                  <el-input v-model="wifi.interfacePar.mac" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" @click="updateWiFi"> 应用 </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div v-else-if="selectedItem == 'Zigbee'">
        Zigbee {{ interfaces.Zigbee }}
      </div>
      <!-- {{ selectedItem }} -->
    </div>
  </div>
</template>

<style scoped sass>
.content {
  width: 98%;
  height: 100%;
  display: flex;
  justify-content: space-around;
}
.content_left {
  width: 120px;
  /* border: 1px solid red; */
  height: 100%;
  border-radius: 5px;
  /* font-size: 0.8rem; */
  /* background-color: #9cbfe9; */
}
.interfaces_item {
  width: 100%;
  height: 26px;
  user-select: none;
  margin: 5px 0;
  border-radius: 5px;
  padding: 0px 15px;
  text-align: left;
  cursor: pointer;
}
.interfaces_item:hover {
  background-color: #d9dcd6;
}

/* 高亮样式 */
.interfaces_item.active {
  background-color: #69a1e5; /* 高亮颜色 */
  color: rgb(255, 255, 255); /* 可选：改变字体颜色 */
}
.content_right {
  /* font-size: 0.8rem !important; */
  width: calc(100% - 140px);
  /* border: 1px solid red; */
  background-color: #dddddd;
  height: 100% !important;
  padding: 5px;
}

.right_form {
  /* border: 1px solid red; */
}
.right_form :deep(.el-form-item--label-top) {
  display: flex !important;
}

/* form前面的label */
.right_form :deep(.el-form-item__label) {
  line-height: 32px !important;
  margin-bottom: 0 !important;
  width: 82px !important;
  padding-right: 8px !important;
  text-align: right !important;
}
/* 整体的label  value框 */
.right_form :deep(.el-col) {
  padding-left: 15px !important;
  padding-right: 0 !important;
}
/* com口的样式 */

.com_item :deep(.el-card__body) {
  padding: 8px 5px 0px !important;
}
</style>
